package org.jeecg.modules.product.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * java.util.concurrent 包提供了许多高级并发工具，如 ReentrantLock、AtomicInteger、CountDownLatch 等，
 * 可以更灵活地实现多线程同步。下面是一个使用 ReentrantLock 和 AtomicInteger 实现多线程计数的示例。
 *
 * 使用 ReentrantLock 实现多线程计数
 * ReentrantLock 是一个可重入的互斥锁，提供了比 synchronized 更灵活的锁机制。
 */
public class CounterWithReentrantLock {
    private int count = 0;
    private final Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();  // 获取锁
        try {
            count++;
        } finally {
            lock.unlock();  // 释放锁
        }
    }

    public int getCount() {
        lock.lock();  // 获取锁
        try {
            return count;
        } finally {
            lock.unlock();  // 释放锁
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CounterWithReentrantLock counter = new CounterWithReentrantLock();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("Final count: " + counter.getCount()); // 输出应该是2000
    }
}